package sanphone.com.runningschool.Fragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;

import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.GlideImageLoader;
import sanphone.com.runningschool.InterfaceLocation;

import sanphone.com.runningschool.JuShou.JuShouActivity;
import sanphone.com.runningschool.JuShou.Jushou_ListViewAdapter;
import sanphone.com.runningschool.MainActivity;
import sanphone.com.runningschool.MyListView;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;
import sanphone.com.runningschool.entity.JuShouInfo;

import static android.content.Context.MODE_PRIVATE;

// TODO: 2018/8/7 举手之劳页面 
public class JushouFragment extends Fragment {

    private List<JuShouInfo> infos = null;
    private ListView  jushou_listView;
    private Jushou_ListViewAdapter adapter;
    private Integer[] images = {R.drawable.image1, R.drawable.image2,
            R.drawable.image3, R.drawable.image4,R.drawable.school};
    private SharedPreferences sprf;
    private String id;
    private SwipeRefreshLayout refreshLayout;
    private Toolbar toolbar;
    private ForceOffline offline;
    private NestedScrollView nestedScrollView;



    public static JushouFragment newInstance() {
        JushouFragment fragment = new JushouFragment();
        return fragment;
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.jushou_fragment, null);
        sprf = getActivity().getSharedPreferences("data", MODE_PRIVATE);
        id = sprf.getString("schoolId", null);
        toolbar = view.findViewById(R.id.jushou_toolbar);
        toolbar.setTitle("");
        toolbar.inflateMenu(R.menu.jushou_menu);
        ((MainActivity) getActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);

        Banner banner = view.findViewById(R.id.imageBanner);
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(Arrays.asList(images));
        banner.start();
        nestedScrollView=view.findViewById(R.id.nestedScrollView);
        refreshLayout = view.findViewById(R.id.jushou_refresh);
        jushou_listView = view.findViewById(R.id.jushou_info_list_view);
        nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int flag=nestedScrollView.getScrollY();
           if(flag==0){
               refreshLayout.setEnabled(flag==0);
           }else{
               refreshLayout.setEnabled(flag==0);
           }
              }

        });
//        jushou_listView.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//             View firstView=view.getChildAt(firstVisibleItem);
//             if(firstVisibleItem==0&&(firstView==null||firstView.getTop()==0)){
//                 refreshLayout.setEnabled(true);
//             }
//             else {
//                 refreshLayout.setEnabled(false);
//             }
//            }
//        });

        refreshLayout.setColorSchemeResources(R.color.colorPrimary);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                refresh();
            }
        });
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.jushou_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.insert_jushou:
                PopupMenu popupMenu=new PopupMenu(getActivity(),toolbar);
                popupMenu.inflate(R.menu.insert_menu);
                popupMenu.setGravity(Gravity.RIGHT);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.publish:
                                getActivity().startActivity(new Intent(getActivity(), JuShouActivity.class));
                                break;
                        }
                        return true;
                    }
                });
                popupMenu.show();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        offline = new ForceOffline(id, getActivity());
        offline.check();
    }

    public void addData() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                RequestHttp requestHttp = new RequestHttp(InterfaceLocation.getLocation() + "getAllUserBehavior",getActivity());
                try {
                    String response = requestHttp.get();
                    Log.e("jushou", response);
                    String data = new JSONObject(response).getString("data");
                    Gson gson = new Gson();
                    infos = gson.fromJson(data, new TypeToken<List<JuShouInfo>>() {}.getType());
                    Collections.reverse(infos);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter = new Jushou_ListViewAdapter(getActivity(), infos);
                            jushou_listView.setAdapter(adapter);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {

                }

            }
        });
        executorService.shutdown();

    }

    private void refresh() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        addData();
                        offline.check();
                        refreshLayout.setRefreshing(false);
                    }
                });
            }
        }).start();
    }
}
